package com.wwwarehouse.usercenter.fragment.permission_recycle;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.filter.FilterBean;
import com.wwwarehouse.common.bean.response.CardDeskFunctionResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.CustomViewPagerInternal;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.custom_widget.time_pick.DateUtil;
import com.wwwarehouse.common.eventbus_event.DrawerMultipleCompleteEvent;
import com.wwwarehouse.common.fragment.DeskDrawerMultipleFragment;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.common.tripartite_widget.viewindicator.CirclePageIndicator;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.adapter.SelectPermissionPagerAdapter;
import com.wwwarehouse.usercenter.bean.permission_recycle.AuthorizedOutItensBean;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;
import com.wwwarehouse.usercenter.eventbus_event.PREvent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import de.greenrobot.event.EventBus;


/**
 * Created by xiaoke.ni on 2017/10/11.
 *
 */
@Route(path = UserCenterConstant.PATH_AUTHORITY_PR)
public class PRFragment extends BaseFragment implements View.OnClickListener, PRListFragment.OnButtonClickedListener {

    private View mView;

    private StateLayout mStateLayout;
    private ElasticScrollView mElasticScrollView;
    private CustomViewPagerInternal mCustomViewPagerInternal;
    private CirclePageIndicator mCirclePagerIndicator;

    private SelectPermissionPagerAdapter mViewPagerAdapter;

    private List<Fragment> mFragmentList;
    private List<FilterBean> mFilterList;
    private List<ArrayList<AuthorizedOutItensBean.UserCardAuthoritiesBean>> mFragmentDataList;
    private List<AuthorizedOutItensBean.UserCardAuthoritiesBean> mAuthorLinkedList;
    private AuthorizedOutItensBean mAuthorizedOutItensBean;

    private String mUserId;// "19001"
    private String mBusinessUnitId;//"111111"
    private int mSelectedBubblePosition = 2;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = View.inflate(getActivity(), R.layout.fragment_pr, null);
        return mView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initEvent();
    }

    private void initView() {
        mStateLayout = (StateLayout) mView.findViewById(R.id.slt);
        mElasticScrollView = (ElasticScrollView) mView.findViewById(R.id.esv);
        mCustomViewPagerInternal = (CustomViewPagerInternal) mView.findViewById(R.id.cvpi);
        mCirclePagerIndicator = (CirclePageIndicator) mView.findViewById(R.id.cpi);
    }

    private void initEvent() {
    }

    @Override
    public void onButtonClicked() {

    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof PRFragment) {
            mActivity.setTitle(getResources().getString(R.string.user_pr));
        }
    }

    @Override
    public void requestDatas() {
        if (getArguments() != null) {
            Bundle bundle = getArguments();
            CardDeskFunctionResponseBean.TaskBean taskBean = (CardDeskFunctionResponseBean.TaskBean) bundle.getSerializable(Constant.KEY_CARD_DESK_FUNCTION_DETAILS);
            if (taskBean != null)
                mBusinessUnitId = taskBean.getBusinessId();
            mUserId = sp.getValue(Constant.sp_User_Id);
        }
        if (UserCenterConstant.MOCK) {
            mBusinessUnitId = "111111";
            mUserId = "19001";
        }
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mFragmentList = new ArrayList<>();
        mFilterList = new ArrayList<>();
        mFragmentDataList = new ArrayList<>();
        mAuthorLinkedList = new ArrayList<>();
        mStateLayout.showProgressView(true);
        cardDeskOption();
        getAuthorizedOutItems();
    }

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    /**
     * 权限回收-查询用户可以回收的权限项
     */
    private void getAuthorizedOutItems() {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", mUserId);
        map.put("businessId", mBusinessUnitId);
        NoHttpUtils.httpPost(UserCenterConstant.GET_AUTHORIZED_OUT_ITENS, map, onResponseListener, 0);
    }


    private NoHttpUtils.OnResponseListener onResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case 0:
                    if (TextUtils.equals("0", commonClass.getCode())) {
                        mStateLayout.showContentView();
                        mAuthorizedOutItensBean = JSON.parseObject(commonClass.getData().toString(), AuthorizedOutItensBean.class);

                        /******** 设置侧滑菜单 *******/
                        for (AuthorizedOutItensBean.TagsBean bean : mAuthorizedOutItensBean.getTags()) {
                            mFilterList.add(new FilterBean(false, bean.getTagName()));
                        }
                        DeskDrawerMultipleFragment deskDrawerMultipleFragment = DeskDrawerMultipleFragment.newInstance(getResources().getString(R.string.user_pr_application_object), mFilterList, 2);
                        ((BaseCardDeskActivity) mActivity).setDrawerLayout(deskDrawerMultipleFragment);
                        ((BaseCardDeskActivity) mActivity).disableDrawerLayout();
                        /******** 设置侧滑菜单 *******/

                        mAuthorLinkedList.addAll(mAuthorizedOutItensBean.getUserCardAuthorities());
                        // 默认排序：获取权限时间由近到远
                        Collections.sort(mAuthorLinkedList, new Comparator<AuthorizedOutItensBean.UserCardAuthoritiesBean>() {
                            @Override
                            public int compare(AuthorizedOutItensBean.UserCardAuthoritiesBean o1, AuthorizedOutItensBean.UserCardAuthoritiesBean o2) {
                                Date date1 = DateUtil.formatDateStr(o1.getValidDate(), "yyyy-MM-dd HH:mm:ss");
                                Date date2 = DateUtil.formatDateStr(o2.getValidDate(), "yyyy-MM-dd HH:mm:ss");
                                if (date1.after(date2)) {
                                    return -1;
                                } else if (date1.before(date2)) {
                                    return 1;
                                } else {
                                    return 0;
                                }
                            }
                        });
                        // 分页
                        List<AuthorizedOutItensBean.UserCardAuthoritiesBean> list = new ArrayList<>(); // 用来填装item的量具, 最大容量是30
                        for (int i = 0; i < mAuthorLinkedList.size(); i++) {
                            list.add(mAuthorLinkedList.get(i));
                            if (list.size() == 30 || i == mAuthorLinkedList.size() - 1) { // 当填满了30个item或者已经到总数的最后一个时, 将这一页加入到页的集合中
                                ArrayList<AuthorizedOutItensBean.UserCardAuthoritiesBean> perPageList = new ArrayList<>();
                                for (AuthorizedOutItensBean.UserCardAuthoritiesBean itemBean : list) {
                                    perPageList.add(itemBean);
                                }
                                mFragmentDataList.add(perPageList); // 将这一页加入到页的集合中
                                list = new ArrayList<>(); // 清空填装item的容器
                            }
                        }

                        for (ArrayList<AuthorizedOutItensBean.UserCardAuthoritiesBean> dataList : mFragmentDataList) {
                            PRListFragment listFragment = PRListFragment.newInstance(dataList, mBusinessUnitId);
                            listFragment.setOnButtonClickedListener(PRFragment.this);
                            mFragmentList.add(listFragment);
                        }
                        mViewPagerAdapter = new SelectPermissionPagerAdapter(getChildFragmentManager(), mFragmentList);
                        mCustomViewPagerInternal.setAdapter(mViewPagerAdapter);
                        mCirclePagerIndicator.setViewPager(mCustomViewPagerInternal);
                    } else {
                        mStateLayout.showEmptyView(commonClass.getMsg(), true);
                        mStateLayout.setEmptyListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                getAuthorizedOutItems();
                            }
                        });
                        ToastUtils.showToast(commonClass.getMsg());
                    }
                    break;
            }
        }

        @Override
        public void onFailed(String s, int i) {

        }

        @Override
        public void onFinish(int i) {
            dismissProgressDialog();
        }
    };

    @Override
    public void sortClick(View anchor) {
        if (peekFragment() instanceof PRFragment) {
            PopUpUtils.showBubbleInviteSort(getContext(), anchor, mSelectedBubblePosition, new PopUpUtils.OnChoiceListener() {
                @Override
                public void onChoice(int position) {
                    mSelectedBubblePosition = position;

                    switch (position) {
                        case 1:
                            // 获取权限时间由远到近
                            Collections.sort(mAuthorLinkedList, new Comparator<AuthorizedOutItensBean.UserCardAuthoritiesBean>() {
                                @Override
                                public int compare(AuthorizedOutItensBean.UserCardAuthoritiesBean o1, AuthorizedOutItensBean.UserCardAuthoritiesBean o2) {
                                    Date date1 = DateUtil.formatDateStr(o1.getValidDate(), "yyyy-MM-dd HH:mm:ss");
                                    Date date2 = DateUtil.formatDateStr(o2.getValidDate(), "yyyy-MM-dd HH:mm:ss");
                                    if (date1.after(date2)) {
                                        return 1;
                                    } else if (date1.before(date2)) {
                                        return -1;
                                    } else {
                                        return 0;
                                    }
                                }
                            });
                            break;
                        case 2:
                            // 获取权限时间由近到远
                            Collections.sort(mAuthorLinkedList, new Comparator<AuthorizedOutItensBean.UserCardAuthoritiesBean>() {
                                @Override
                                public int compare(AuthorizedOutItensBean.UserCardAuthoritiesBean o1, AuthorizedOutItensBean.UserCardAuthoritiesBean o2) {
                                    Date date1 = DateUtil.formatDateStr(o1.getValidDate(), "yyyy-MM-dd HH:mm:ss");
                                    Date date2 = DateUtil.formatDateStr(o2.getValidDate(), "yyyy-MM-dd HH:mm:ss");
                                    if (date1.after(date2)) {
                                        return -1;
                                    } else if (date1.before(date2)) {
                                        return 1;
                                    } else {
                                        return 0;
                                    }
                                }
                            });

                            break;
                        default:
                            break;
                    }
                    mFragmentDataList.clear();
                    // 分页
                    List<AuthorizedOutItensBean.UserCardAuthoritiesBean> list = new ArrayList<>(); // 用来填装item的量具, 最大容量是30
                    for (int i = 0; i < mAuthorLinkedList.size(); i++) {
                        list.add(mAuthorLinkedList.get(i));
                        if (list.size() == 30 || i == mAuthorLinkedList.size() - 1) { // 当填满了30个item或者已经到总数的最后一个时, 将这一页加入到页的集合中
                            ArrayList<AuthorizedOutItensBean.UserCardAuthoritiesBean> perPageList = new ArrayList<>();
                            for (AuthorizedOutItensBean.UserCardAuthoritiesBean itemBean : list) {
                                perPageList.add(itemBean);
                            }
                            mFragmentDataList.add(perPageList); // 将这一页加入到页的集合中
                            list = new ArrayList<>(); // 清空填装item的容器
                        }
                    }
                    mFragmentList.clear();
                    for (ArrayList<AuthorizedOutItensBean.UserCardAuthoritiesBean> dataList : mFragmentDataList) {
                        PRListFragment listFragment = PRListFragment.newInstance(dataList, mBusinessUnitId);
                        listFragment.setOnButtonClickedListener(PRFragment.this);
                        mFragmentList.add(listFragment);
                    }
                    mCustomViewPagerInternal.removeAllViews();
                    mViewPagerAdapter = new SelectPermissionPagerAdapter(getChildFragmentManager(), mFragmentList);
                    mCustomViewPagerInternal.setAdapter(mViewPagerAdapter);
                    mCirclePagerIndicator.setViewPager(mCustomViewPagerInternal);
                    mViewPagerAdapter.notifyDataSetChanged();
                }
            }, null, "获取权限时间由远到近", "获取权限时间由近到远");
        }
    }

    @Override
    public void searchNoRealTimeClick(String text) {
        if (peekFragment() instanceof PRFragment) {
            List<AuthorizedOutItensBean.UserCardAuthoritiesBean> tempList = new ArrayList<>();
            for (AuthorizedOutItensBean.UserCardAuthoritiesBean itemBean : mAuthorLinkedList) {
                if (itemBean.getCardName() != null && itemBean.getCardName().contains(text)) {
                    tempList.add(itemBean);
                }
            }

            mFragmentDataList.clear();
            // 分页
            List<AuthorizedOutItensBean.UserCardAuthoritiesBean> list = new ArrayList<>(); // 用来填装item的量具, 最大容量是30
            for (int i = 0; i < tempList.size(); i++) {
                list.add(tempList.get(i));
                if (list.size() == 30 || i == tempList.size() - 1) { // 当填满了30个item或者已经到总数的最后一个时, 将这一页加入到页的集合中
                    ArrayList<AuthorizedOutItensBean.UserCardAuthoritiesBean> perPageList = new ArrayList<>();
                    for (AuthorizedOutItensBean.UserCardAuthoritiesBean itemBean : list) {
                        perPageList.add(itemBean);
                    }
                    mFragmentDataList.add(perPageList); // 将这一页加入到页的集合中
                    list = new ArrayList<>(); // 清空填装item的容器
                }
            }
            mFragmentList.clear();
            for (ArrayList<AuthorizedOutItensBean.UserCardAuthoritiesBean> dataList : mFragmentDataList) {
                PRListFragment listFragment = PRListFragment.newInstance(dataList, mBusinessUnitId);
                listFragment.setOnButtonClickedListener(PRFragment.this);
                mFragmentList.add(listFragment);
            }
            mCustomViewPagerInternal.removeAllViews();
            mViewPagerAdapter = new SelectPermissionPagerAdapter(getChildFragmentManager(), mFragmentList);
            mCustomViewPagerInternal.setAdapter(mViewPagerAdapter);
            mCirclePagerIndicator.setViewPager(mCustomViewPagerInternal);
            mCirclePagerIndicator.requestLayout();
            mViewPagerAdapter.notifyDataSetChanged();
        }
    }

    private void cardDeskOption() {
        mElasticScrollView.setOnPullListener(new ElasticScrollView.OnPullListener() {
            @Override
            public void onDownPull() {
                ((BaseCardDeskActivity) mActivity).downPull_4();
            }

            @Override
            public void onUpPull() {

            }
        });

    }


    @Override
    public void filterClick() {
        if (peekFragment() instanceof PRFragment) {
            ((BaseCardDeskActivity) mActivity).showDrawerLayout();
        }
    }

    @Override
    public void cancelClick() {
        if (peekFragment() instanceof PRFragment) {
            mFragmentDataList.clear();
            // 分页
            List<AuthorizedOutItensBean.UserCardAuthoritiesBean> list = new ArrayList<>(); // 用来填装item的量具, 最大容量是30
            for (int i = 0; i < mAuthorLinkedList.size(); i++) {
                list.add(mAuthorLinkedList.get(i));
                if (list.size() == 30 || i == mAuthorLinkedList.size() - 1) { // 当填满了30个item或者已经到总数的最后一个时, 将这一页加入到页的集合中
                    ArrayList<AuthorizedOutItensBean.UserCardAuthoritiesBean> perPageList = new ArrayList<>();
                    for (AuthorizedOutItensBean.UserCardAuthoritiesBean itemBean : list) {
                        perPageList.add(itemBean);
                    }
                    mFragmentDataList.add(perPageList); // 将这一页加入到页的集合中
                    list = new ArrayList<>(); // 清空填装item的容器
                }
            }
            mFragmentList.clear();
            for (ArrayList<AuthorizedOutItensBean.UserCardAuthoritiesBean> dataList : mFragmentDataList) {
                PRListFragment listFragment = PRListFragment.newInstance(dataList, mBusinessUnitId);
                listFragment.setOnButtonClickedListener(PRFragment.this);
                mFragmentList.add(listFragment);
            }
            mCustomViewPagerInternal.removeAllViews();
            mViewPagerAdapter = new SelectPermissionPagerAdapter(getChildFragmentManager(), mFragmentList);
            mCustomViewPagerInternal.setAdapter(mViewPagerAdapter);
            mCirclePagerIndicator.setViewPager(mCustomViewPagerInternal);
            mViewPagerAdapter.notifyDataSetChanged();
        }
    }

    //刷新数据

    public void onEventMainThread(PREvent event) {
        String message = event.getMsg();
        if ("pr_refresh".equals(message)) {
            mFragmentList = new ArrayList<>();
            mFilterList = new ArrayList<>();
            mFragmentDataList = new ArrayList<>();
            mAuthorLinkedList = new ArrayList<>();
            mStateLayout.showProgressView(true);
            cardDeskOption();
            getAuthorizedOutItems();
        }
    }

    public void onEventMainThread(DrawerMultipleCompleteEvent event) {
        if (!(peekFragment() instanceof PRFragment) && mAuthorizedOutItensBean != null) {
            return;
        }
        ((BaseCardDeskActivity) mActivity).hideDrawerLayout();
        Set<Integer> set = event.getSelectedPositionSet();
        List<String> filterBeanList = new ArrayList<>();
        if (set.isEmpty()) {
            for (FilterBean filterBean : mFilterList) {
                filterBeanList.add(filterBean.getText());
            }
        } else {
            for (Integer i : set) {
                filterBeanList.add(mFilterList.get(i).getText());
            }
        }
        mAuthorLinkedList.clear();
        for (AuthorizedOutItensBean.UserCardAuthoritiesBean itemBean : mAuthorizedOutItensBean.getUserCardAuthorities()) {
            if (filterBeanList.contains(itemBean.getTagName())) {
                mAuthorLinkedList.add(itemBean);
            }
        }

        mFragmentDataList.clear();
        // 分页
        List<AuthorizedOutItensBean.UserCardAuthoritiesBean> list = new ArrayList<>(); // 用来填装item的量具, 最大容量是30
        for (int i = 0; i < mAuthorLinkedList.size(); i++) {
            list.add(mAuthorLinkedList.get(i));
            if (list.size() == 30 || i == mAuthorLinkedList.size() - 1) { // 当填满了30个item或者已经到总数的最后一个时, 将这一页加入到页的集合中
                ArrayList<AuthorizedOutItensBean.UserCardAuthoritiesBean> perPageList = new ArrayList<>();
                for (AuthorizedOutItensBean.UserCardAuthoritiesBean itemBean : list) {
                    perPageList.add(itemBean);
                }
                mFragmentDataList.add(perPageList); // 将这一页加入到页的集合中
                list = new ArrayList<>(); // 清空填装item的容器
            }
        }
        mFragmentList.clear();
        for (ArrayList<AuthorizedOutItensBean.UserCardAuthoritiesBean> dataList : mFragmentDataList) {
            PRListFragment listFragment = PRListFragment.newInstance(dataList, mBusinessUnitId);
            listFragment.setOnButtonClickedListener(PRFragment.this);
            mFragmentList.add(listFragment);
        }
        mCustomViewPagerInternal.removeAllViews();
        mViewPagerAdapter = new SelectPermissionPagerAdapter(getChildFragmentManager(), mFragmentList);
        mCustomViewPagerInternal.setAdapter(mViewPagerAdapter);
        mCirclePagerIndicator.setViewPager(mCustomViewPagerInternal);
        mCirclePagerIndicator.requestLayout();
        mViewPagerAdapter.notifyDataSetChanged();

    }

}
